let driverNumber = ''
let driver_id = ''
//云开发
const db = wx.cloud.database()
const users = db.collection('users')
//云函数
let setGoods = null
let setWorkState = null
//实时数据推送
let usersGoods = null
let driverGoods = null
let driverAccount = null
let allUserGoods = null
//markers点
let otherDriverMarkers = []
let userMarkers = []
//节流阀
let f = true
let work = true
//获取用户定位
let locationBoolean = true
Page({
  data: {
    workBtnN: '',
    workImg: 'work-y',
    workShow: true,
    yBtn: 'y-btn',
    nBtn: '',
    latitude: '',
    longitude: '',
    scale: '17',
    markers: [],
    newList: [],
    yWorkList: [],
    nWorkList: [],
    workBoxAnimation: 'work-box-animation-to'
  },
  onLoad(options) {
    let that = this
    driverNumber = options.number
    driver_id = options.driver_id
    console.log(driverNumber, driver_id)
    //获取用户的地理坐标 
    that.getUserLocation()
    //地图实例
    that.mapCtx = wx.createMapContext('myMap')
    //地图中心偏移
    that.mapCtx.setCenterOffset({
      offset: [0.5, 0.25]
    })
    //显示其它司机的位置
    that.watchDriverAccount()
    //显示用户位置
    that.watchAllUserGoods()
  },
  //获取司机位置
  getUserLocation() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3000,
      success(res) {
        console.log('获取用户当前位置成功', res)
        locationBoolean = true
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: '17',
        })
      },
      fail(err) {
        console.log('获取用户当前位置失败', err)
        if (!err.errCode) {
          console.log('请勿频繁点击')
          that.setData({
            latitude: that.data.latitude,
            longitude: that.data.longitude,
            scale: '17',
          })
        } else {
          console.log('请打开手机定位')
          if (locationBoolean) {
            locationBoolean = false
            wx.showModal({
              title: '',
              showCancel: false,
              content: '请开启手机定位',
              success(res) {
                //用户点击确定
                if (res.confirm) {
                  //3s后自动调用一次
                  setTimeout(() => {
                    that.getUserLocation()
                  }, 1000)
                }
              }
            })
          } else {
            //3s后自动调用一次
            setTimeout(() => {
              that.getUserLocation()
            }, 1000)
          }
        }
      }
    })
  },
  //##############界面操作
  //点击进行中和接单按钮
  onWorkShow(e) {
    let that = this
    switch (e.currentTarget.dataset.type) {
      case 'y':
        console.log('点击了已接订单')
        that.setData({
          workShow: true,
          yBtn: 'y-btn',
          nBtn: '',
        })
        break;
      case 'n':
        console.log('点击了未接订单')
        that.setData({
          workShow: false,
          yBtn: '',
          nBtn: 'y-btn',
        })
        break;
    }
  },
  //点击跳转司机页面
  onDriver() {
    console.log('点击跳转司机页面')
    wx.navigateTo({
      url: '/pages/driver/driver?driverNumber=' + driverNumber + '&driver_id=' + driver_id
    })
  },
  //点击开工
  onWork() {
    console.log('点击开工')
    let that = this
    if (!work) return
    work = false
    if (that.data.workImg === 'work-y') {
      //开工
      //判断是否授权,并开启后台定位,更新司机位置
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userLocationBackground']) {
            wx.authorize({
              scope: 'scope.userLocationBackground',
              success() {
                console.log('成功开启后台定位授权')
                wx.startLocationUpdateBackground({
                  type: 'gcj02',
                  success() {
                    wx.onLocationChange(data => {
                      console.log('成功', data)
                      //调用updateDriverLocation云函数更新司机位置
                      wx.cloud.callFunction({
                        name: 'updateDriverLocation',
                        data: {
                          number: driverNumber,
                          latitude: data.latitude,
                          longitude: data.longitude,
                        }
                      })
                      work = true
                    })
                  }
                })
              }
            })
            //修改工作状态为true
            that.setWorkState(true)
            setWorkState.then(() => {
              that.setData({
                workBtnN: 'work-btn-n',
                workImg: 'work-n',
              })
            })
            that.watchUsersGoods()
            that.watchDriverGoods()
            wx.showToast({
              title: '开始接单，祝您工作愉快！',
              icon: 'none',
              duration: 1000,
            })
          } else {
            wx.showModal({
              title: '',
              content: '位置权限请选择使用时和离开后',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: (res) => {
                      console.log('用户修改授权')
                      work = true
                    }
                  })
                }
              }
            })
          }
        }
      })

    } else {
      //休息
      wx.showModal({
        title: '下班提醒',
        content: '下班后将无法继续接单，是否确定？',
        success(res) {
          if (res.confirm) {
            //修改工作状态为false
            that.setWorkState(false)
            setWorkState.then(() => {
              that.setData({
                workBtnN: '',
                workImg: 'work-y',
              })
            })
            wx.offLocationChange()
            usersGoods.close()
            driverGoods.close()
            work = true
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  //点击回到司机位置
  onPitch() {
    let that = this
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3000,
      success(res) {
        console.log('获取用户当前位置成功', res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: '17',
        })
      }
    })
    that.mapCtx.moveToLocation()
  },
  //点击接单按钮
  onNWork(id) {
    let that = this
    console.log('点击大接单按钮', id.currentTarget.dataset.id)
    let _id = id.currentTarget.dataset.id
    that.setGoods(_id)
    let index = that.data.newList.findIndex(item => {
      return item._id == _id
    })
    if (index !== -1) {
      that.data.newList.splice(index, 1)
      that.setData({
        newList: that.data.newList
      })
    }
  },
  //点击完成订单按钮
  onYWork(openid) {
    console.log('点击完成订单按钮', openid.currentTarget.dataset.openid)
    //调用云函数clearUsers
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: 'clearUserAllMessage',
      data: {
        openid: openid.currentTarget.dataset.openid
      }
    }).then(res => {
      console.log('清除成功')
      // 关闭加载
      wx.hideLoading()
    })
  },
  //点击接单页面的伸缩动画
  onWorkBoxAnimation() {
    let that = this
    if (that.data.workBoxAnimation === 'work-box-animation-from' || that.data.workBoxAnimation === '') {
      that.setData({
        workBoxAnimation: 'work-box-animation-to'
      })
      that.mapCtx.setCenterOffset({
        offset: [0.5, 0.25],
      })

    } else {
      that.setData({
        workBoxAnimation: 'work-box-animation-from'
      })
      that.mapCtx.setCenterOffset({
        offset: [0.5, 0.5],
      })
    }
  },
  //点击订单跳转到对应的标记点位置
  onGoodsMoveLocation(e) {
    let that = this
    let latitude = e.currentTarget.dataset.latitude
    let longitude = e.currentTarget.dataset.longitude
    console.log(e.currentTarget.dataset)
    if (f) {
      f = false
      that.mapCtx.moveToLocation({
        longitude: longitude,
        latitude: latitude,
        success() {
          setTimeout(() => {
            that.mapCtx.moveToLocation()
            f = true
          }, 3000)
        }
      })
      that.setData({
        scale: '17'
      })
    }
  },
  //####内部调用的函数
  //####云函数
  //监听users表
  watchUsersGoods() {
    let that = this
    usersGoods = db.collection('users').where({
      state: 0
    }).watch({
      onChange(res) {
        console.log('监听users成功', res)
        let nWorkList = res.docs
        that.setData({
          nWorkList,
        })
        if (res.type !== "init" && res.docChanges[0].doc.state === 0) {
          let newList = res.docChanges[0].doc
          let _id = newList._id
          that.data.newList.push(newList);
          that.setData({
            newList: that.data.newList
          })
          console.log(that.data.newList)
          setTimeout(() => {
            let index = that.data.newList.findIndex(item => {
              return item._id == _id
            })
            if (index !== -1) {
              that.data.newList.splice(index, 1)
              that.setData({
                newList: that.data.newList
              })
            }
          }, 10000)
        }
      },
      onError(err) {
        console.log('监听messages失败', err)
      }
    })
  },
  watchAllUserGoods() {
    let that = this
    allUserGoods = db.collection('users').watch({
      onChange(res) {
        console.log('监听allUserGoods成功', res)
        let list = res.docs
        userMarkers = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].state === 0) {
            userMarkers.push({
              id: i + 1,
              latitude: list[i].latitude,
              longitude: list[i].longitude,
              iconPath: '/image/icom/user-n.png',
              width: 36,
              height: 72
            })
          } else {
            userMarkers.push({
              id: i + 1,
              latitude: list[i].latitude,
              longitude: list[i].longitude,
              iconPath: '/image/icom/user.png',
              width: 36,
              height: 72
            })
          }
          console.log('用户', userMarkers, that.data.markers)
        }
        that.data.markers = [...otherDriverMarkers, ...userMarkers]
        that.setData({
          markers: that.data.markers
        })
      },
      onError(err) {
        console.log('监听allUserGoods失败', err)
      }
    })
  },
  //监听司机已接单表
  watchDriverGoods() {
    let that = this
    driverGoods = db.collection('driver_goods_' + driverNumber).watch({
      onChange(res) {
        console.log('成功监听driver_goods_' + driverNumber, res)
        let yWorkList = res.docs
        that.setData({
          yWorkList,
        })
      },
      onError(err) {
        console.log('监听失败driver_goods_' + driverNumber, err)
      }
    })
  },
  //监听其它司机位置的变化
  watchDriverAccount() {
    let that = this
    driverAccount = db.collection('driver_account').where({
      state: true
    }).watch({
      onChange(res) {
        console.log('成功监听driver_account', res)
        let list = res.docs
        let index = list.findIndex(item => item.number === driverNumber)
        if (index !== -1) {
          list.splice(index, 1)
        }
        otherDriverMarkers = []
        for (let i = 0; i < list.length; i++) {
          otherDriverMarkers.push({
            id: - i - 1,
            latitude: list[i].latitude,
            longitude: list[i].longitude,
            iconPath: '/image/icom/driverlo.png',
            width: 36,
            height: 72
          })
        }
        that.data.markers = [...otherDriverMarkers, ...userMarkers]
        that.setData({
          markers: that.data.markers
        })
        console.log('司机', otherDriverMarkers, that.data.markers)
      },
      onError(err) {
        console.log('监听失败driver_account', err)
      }
    })
  },
  //通过调用setGoods云函数来接单
  setGoods(id) {
    wx.cloud.callFunction({
      name: 'setGoods',
      data: {
        _id: id,
        number: driverNumber
      }
    })
  },
  //调用云函数setWorkState云函数，更新司机工作状态
  setWorkState(workState) {
    setWorkState = wx.cloud.callFunction({
      name: 'setWorkState',
      data: {
        work_state: workState,
        number: driverNumber
      }
    })
  }
})